package com.klasster.recruitmentPlatform.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.klasster.recruitmentPlatform.common.response.Result;
import com.klasster.recruitmentPlatform.common.response.ResultCode;
import com.klasster.recruitmentPlatform.common.util.TokenUtil;
import com.klasster.recruitmentPlatform.controller.UserController;
import com.klasster.recruitmentPlatform.domain.vo.UserVO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

/**
 * token拦截器
 */
@Component
@RequiredArgsConstructor
public class TokenInterceptor implements HandlerInterceptor {

    private final TokenUtil tokenUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(request.getRequestURI());
        //获取token
        String token = request.getHeader("token");
        if(StrUtil.isBlank(token)) {
            token = request.getParameter("token");
        }
        //token不可为空
        if(StrUtil.isBlank(token)) {
            sendResponse(response,Result.error(ResultCode.AUTH_UN_LOGIN,null));
            return false;
        }
        //验证token有效性
        if(!tokenUtil.checkToken(token)) {
            sendResponse(response,Result.error(ResultCode.AUTH_TOKEN_INVALID,null));
            return false;
        }
        return true;
    }

    /**
     * 设置响应
     */
    private void sendResponse(HttpServletResponse response, Result result) throws IOException {
        response.setStatus(HttpStatus.BAD_REQUEST.value());
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(convertObjectToJson(result));
        response.getWriter().flush();
    }

    /**
     * 将响应体转化为json传递到前端
     */
    private String convertObjectToJson(Result result) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(result);
    }

}
